package com.bodu.system.service.impl;

import com.bodu.core.entity.ParamReq;
import com.bodu.core.entity.result.Result;
import com.bodu.system.entity.po.StorageConfigPo;
import com.bodu.system.entity.request.FileRequest;
import com.bodu.system.entity.vo.FileVo;
import com.bodu.system.enums.StorageTypeEnums;
import com.bodu.system.mapper.FileMapper;
import com.bodu.system.mapper.StorageConfigMapper;
import com.bodu.system.service.FileService;
import com.bodu.system.template.storage.StorageFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * 系统文件 Service impl
 *
 * @author Administrator
 */
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private FileMapper fileMapper;

    private final StorageFactory storageFactory;

    private final StorageConfigMapper storageConfigMapper;

    public FileServiceImpl(StorageFactory storageFactory, StorageConfigMapper storageConfigMapper) {
        this.storageFactory = storageFactory;
        this.storageConfigMapper = storageConfigMapper;
    }

    @Override
    public FileVo getModel(Long id) {
        FileVo fileVo = fileMapper.getModel(id);
        StorageConfigPo storageConfigPo = storageConfigMapper.getModel(fileVo.getStorageConfigId());
        fileVo.setStorageConfigName(StorageTypeEnums.getStatusValues(storageConfigPo.getStorageType()));
        return fileVo;
    }

    @Transactional
    @Override
    public Long save(FileRequest request) {
        fileMapper.save(request);
        return request.getId();
    }

    @Transactional
    @Override
    public Long update(FileRequest request) {
        fileMapper.update(request);
        return request.getId();
    }

    @Override
    public List<FileVo> listPage(ParamReq<FileRequest> params) {
        List<FileVo> res = fileMapper.listPage(params);
        res.forEach(r -> {
            StorageConfigPo storageConfigPo = storageConfigMapper.getModel(r.getStorageConfigId());
            r.setStorageConfigName(StorageTypeEnums.getStatusValues(storageConfigPo.getStorageType()));
        });

        return res;
    }

    @Override
    public Integer countPage(ParamReq<FileRequest> params) {
        return fileMapper.countPage(params);
    }

    @Override
    public Integer updateDelFlagById(Long id, Integer delFlag) {
        return fileMapper.updateDelFlagById(id, delFlag);
    }

    @Transactional
    @Override
    public Result uploadFile(MultipartFile[] files) {
        return storageFactory.saveFile(files);
    }
}
